package server.netty;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import newtank.network.server.handler.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 请求处理器
 * @author lijiahao
 */
public class NettyGpcRequestHandler extends ChannelInboundHandlerAdapter {

	private static final Map<Integer, BossDataHandler> INNER_DATA_HANDLER_MAP = new HashMap<>();

	private static final EnvironmentLoadDataHandler environmentLoadDataHandler = new EnvironmentLoadDataHandler();

	static {
		INNER_DATA_HANDLER_MAP.put(0, environmentLoadDataHandler);
		INNER_DATA_HANDLER_MAP.put(10, new MoveDataHandler());
		INNER_DATA_HANDLER_MAP.put(11, new PositionSyncHandler());
		INNER_DATA_HANDLER_MAP.put(20, new ShootDataHandler());
		INNER_DATA_HANDLER_MAP.put(200, new ConnectionDataHandler());
	}

	public static EnvironmentLoadDataHandler getEnvironmentLoadDataHandler() {
		return environmentLoadDataHandler;
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		try {
			System.out.println("接收数据: "+ JSONObject.toJSONString(msg));
			GpcDataPackage request = (GpcDataPackage) msg;
			//数据报分发到处理器处理
			routerAdapter(ctx,request);
		} finally {
			// 抛弃收到的数据
			ReferenceCountUtil.release(msg);
		}
	}
	
	private void routerAdapter(ChannelHandlerContext ctx, GpcDataPackage request) {
		BossDataHandler adapter = INNER_DATA_HANDLER_MAP.get(request.getCode());
		if(adapter == null) {
			throw new NullPointerException();
		}
		adapter.handle(ctx, request);
	}

	/**
	 * 当Netty由于IO错误或者处理器在处理事件时抛出异常时调用
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// 当出现异常就关闭连接
		cause.printStackTrace();
		ctx.close();
	}



}
